﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;

namespace ZX.WebApp.EHR
{
    public partial class hrImportGJJ : BasePage
    {
        static string resFileName = "";
        string flag = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return string.Empty;

            FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
            string path = Request.PhysicalApplicationPath + "upload/EHR/";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            resFileName = path + fileInfo.Name;
            uploadedFile.SaveAs(resFileName);

            RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
            string fileLabel = fileInfo.Name;
            string fileLength = uploadedFile.ContentLength / 1024 + "K";
            return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            /// <summary>
            /// 所有上传数据
            /// </summary>
            IList<DataTable> lstImportData = null;
            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);
                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }
                    if (lstImportData.Count > 0)
                    {
                        DbSql dbsql = new DbSql();
                        string insertSql = "insert into xzEmpGJJ([ID],[EmployeeID],[YearMonth]) values(NEWID(),'{0}','{1}')";
                        string updateSql = @"UPDATE xzEmpGJJ SET [Laborage] ={0} ,[EmpReate] ={1},[CoReate] ={2} ,[PayMoney] ={3} where ID='{4}' ";

                        foreach (DataTable dt in lstImportData)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                string IDCardNO = dr["身份证号码"].ToString().Trim();
                                if (IDCardNO == "")
                                {
                                    continue;
                                }

                                string houseCardNO = dr["个人公积金账号"].ToString().Trim();
                                Dictionary<string, string> dicEmpInfo = GetEmpInfos(IDCardNO, houseCardNO);
                                if (dicEmpInfo.Count > 0)
                                {
                                    string employeeID = dicEmpInfo["EmployeeID"];
                                    string employeeName = dicEmpInfo["EmployeeName"];
                                    string employeeCode = dicEmpInfo["EmployeeCode"];
                                    string yearMonth = dr["缴存月份"].ToString();

                                    decimal laborage = 0, empReate = 0, coReate = 0, PayMoney = 0;
                                    string id = "";

                                    decimal.TryParse(dr["缴存基数"].ToString(), out laborage);
                                    decimal.TryParse(dr["单位缴存比例"].ToString(), out coReate);
                                    decimal.TryParse(dr["个人缴存比例"].ToString(), out empReate);

                                    decimal.TryParse(dr["缴存额"].ToString(), out PayMoney);

                                    //首先判断当月是否有此员工记录，无则写入基本信息
                                    id = IsExistsData(employeeID, yearMonth);
                                    if (id == "")
                                    {
                                        dbsql.ExecuteSql(string.Format(insertSql, employeeID, yearMonth));
                                        id = IsExistsData(employeeID, yearMonth);
                                    }
                                    //更新UPDATE xzEmpGJJ SET [Laborage] ={0} ,[EmpReate] ={1},[CoReate] ={2} ,[PayMoney] ={3} where ID='{4}'
                                    dbsql.ExecuteSql(string.Format(updateSql, laborage, empReate, coReate, PayMoney, id));
                                }
                            }
                        }
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("读取EXCEL为空,请检查文件,可能Sheet未命名为Sheet1或没有数据!");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("文件未上传");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);//出错了
                throw ;
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的个人身份证号码码，匹配员工信息
        /// </summary>
        /// <param name="IDCardNO">身份证号码码</param>
        /// <param name="houseCardNO">个人公积金账号</param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string IDCardNO, string houseCardNO)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("IDCardNO='{0}'", IDCardNO);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);

                //更新个人公积金账号
                if (hrEmployee.SocialInsuranceNO.Trim() != houseCardNO)
                {
                    UpdateEmpHouseCardNO(hrEmployee.ID.ToString(), houseCardNO);
                }
            }
            return dic;
        }

        /// <summary>
        /// 员工导入月份的数据是否已经存在了
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="YearMonth"></param>
        /// <returns></returns>
        protected string IsExistsData(string employeeId, string YearMonth)
        {
            string id = "";
            xzEmpGJJ instance = ZX.Common.Globals.getEntity("xzEmpGJJ") as xzEmpGJJ;
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeID='{0}' and YearMonth='{1}' ", employeeId, YearMonth);
            ZX.EHR.Library.xzEmpGJJ xzEmpGJJ = bll.GetEntityByCondition(condition) as ZX.EHR.Library.xzEmpGJJ;
            if (xzEmpGJJ != null)
            {
                id = xzEmpGJJ.ID.ToString();
            }
            return id;
        }

        /// <summary>
        /// 更新员工个人公积金号
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="houseCardNO"></param>
        /// <returns></returns>
        protected bool UpdateEmpHouseCardNO(string employeeId, string houseCardNO)
        {
            bool result = false;
            DbSql dbSq = new DbSql();
            string sql = string.Format("Update hrEmployee Set  houseCardNO='{0}' where ID='{1}' ", houseCardNO, employeeId);
            result = dbSq.ExecuteSql(sql) > 0;
            return result;
        }
    }
}